package com.fbty.mt.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.fbty.base.dao.MtJdbcDao;
import com.fbty.base.domain.Page;
import com.fbty.mt.dao.PriceDao;
import com.fbty.mt.dao.RecordDao;
import com.fbty.mt.dao.UserDao;
import com.fbty.mt.dao.UserTempDao;
import com.fbty.mt.domain.MailSenderInfo;
import com.fbty.mt.domain.Price;
import com.fbty.mt.domain.Record;
import com.fbty.mt.domain.User;
import com.fbty.mt.domain.UserTemp;
import com.fbty.mt.service.UserService;
import com.fbty.mt.utils.SimpleMailSender;
/**
 * 用户登陆服务类
 * @author thinkpad
 *
 */
public class UserServiceImpl implements UserService{
	private MtJdbcDao mtJdbcDao;
	private UserDao userDao;
	private UserTempDao userTempDao;
	private PriceDao priceDao;
	
	private RecordDao recordDao;
	
	@Override
	public int saveUser(User user) {
		
		String hql = " from User where email='"+user.getEmail()+"'";
		List<User> list = userDao.find(hql);
		if(list.size()>0) {
			return  -1;
		}
		hql = " from User where username='"+user.getUsername()+"'";
		List<User> list1 = userDao.find(hql);
		if(list1.size()>0) {
			return  -2;
		}
		int id = (Integer)userDao.create(user);
		return id;
	}
	/**
	 * 分页查询出所有的用户
	 */
	@Override
	public Page pageUser(Integer pageNo, Integer pageSize,Map<String,String> parms) {
		String sql = " SELECT tu.id,tu.name,tu.password,tu.username,tu.sex,tu.email,tu.phone,tu.qq,tr.title,tr.id as rid "+
					 " FROM tab_user tu LEFT JOIN user2role ur ON tu.id=ur.uid "+
					 " LEFT JOIN tab_role tr ON ur.rid=tr.id where 1=1 ";
		
		if(parms.get("name") != null && !"".equals(parms.get("name"))) {
			sql += " and tu.name like '%?%' ";
		}
		if(parms.get("username") != null && !"".equals(parms.get("username"))) {
			sql += " and tu.username like '%?%' ";
		}
		if(parms.get("roleId") != null && !"".equals(parms.get("roleId"))) {
			sql += " and ur.rid=? ";
		}
		List list = mtJdbcDao.getJdbcTemplate().queryForList(sql);
		Integer count = list.size();
		return new Page(list, pageNo*pageSize, count, pageSize);
	}
	/**
	 * 改更用户角色
	 */
	public void updateTitle(Integer uid,Integer rid) {
		String sql = " update user2role set rid="+rid+" where uid="+uid;
		mtJdbcDao.getJdbcTemplate().update(sql);
	}
	/**
	 * 针对包月用户和独享用户
	 * 通过userId找到该用户还有多少条可用条数
	 * 根据tab_recharge这张表的date字段和当前时间进行比较，如果大于30天，说明该记录拥有的条数就失效
	 * 最后要更新user类里面的num
	 * @return
	 */
	public Integer getNum(Integer uid) {
		String sql = "SELECT num FROM  tab_user WHERE id=?";
		
		int i = mtJdbcDao.getJdbcTemplate().queryForInt(sql, new Object[]{uid});
		
		return i;
		
	}
	/**
	 * 两个时间相减得到天数
	 * @param d1 当前时间
	 * @param d2 开始时间
	 * @return
	 */
	private long getdate(String d1, String d2) {
		   long i = -1;
		   try {
		    SimpleDateFormat formatter = new SimpleDateFormat(
		      "yyyy-MM-dd HH:mm:ss");
		    ParsePosition pos = new ParsePosition(0);
		    ParsePosition pos1 = new ParsePosition(0);
		    Date dt1 = formatter.parse(d1, pos);
		    Date dt2 = formatter.parse(d2, pos1);
		    long l = dt1.getTime() - dt2.getTime();
		    i = l / (1000 * 60 * 60 * 24);
		    // 这是他们相差的天数。
		    System.out.println("Hello World!=" + i);
		   } catch (Exception e) {
		    System.out.println("exception" + e.toString());
		   }
		   return i;
		}

	@Override
	public void deleteUser(Integer uid) {
		userDao.removeById(uid);
	}

	@Override
	public void updateUser(User user) {
		userDao.update(user);
	}
	@Override
	public User findUserById(Integer uid) {
		return userDao.get(uid);
	}
	public MtJdbcDao getMtJdbcDao() {
		return mtJdbcDao;
	}
	public void setMtJdbcDao(MtJdbcDao mtJdbcDao) {
		this.mtJdbcDao = mtJdbcDao;
	}
	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	@Override
	public User findByUsername(String username) {
		String hql = "from User u where u.username =?";
		List<User> list  = userDao.find(hql, username);
		return list.size()>0?list.get(0):null;
	}
	@Override
	public Page pageUser(Integer pageNo, Integer pageSize, String username) {
		String hql = "from User u where u.username like ? order by state desc";
		return userDao.pagedQuery(hql, pageNo, pageSize, new Object[]{username});
	}
	@Override
	public Integer updateMonthNum(Integer uid) {
		String hql = "from Record r where r.uid = ? and r.state=1";
		List<Record> list = recordDao.find(hql, new Object[]{uid});
		Calendar c1 = Calendar.getInstance();
		c1.setTime(new Date());
		User u = userDao.get(uid);
		int total = 0;
		int num = u.getMonthnum();
		for(Record r : list){
			Price p = priceDao.get(r.getPid());
			Calendar c2 = Calendar.getInstance();
			c2.setTime(r.getBuyDate());
			int i = c1.get(Calendar.DAY_OF_YEAR) - c2.get(Calendar.DAY_OF_YEAR);
			if(i!=r.getNum()&&p.getType()==2){
				total += p.getNum();
				r.setNum(i);
				if(i>30){
					r.setState(2);
				}
				recordDao.update(r);
			}
		}
		if(total==0){
			u.setMonthnum(num);
		}else{
			u.setMonthnum(total);
		}
		userDao.update(u);
		return u.getMonthnum();
	}
	
	public Boolean sendEmail(String code) {
		  Properties prop = new Properties();   
		  InputStream in = Object.class.getResourceAsStream("/conf/email.properties");   
		  try {
			prop.load(in);
			String formEmail = prop.getProperty("formEmail");
			String pwd = prop.getProperty("pwd");
			String toEmail = prop.getProperty("toEmail");
			String host = prop.getProperty("host");
			String port = prop.getProperty("port");
			
			if(formEmail == null && "".equals(formEmail)) {
				return false;
			}
			if(pwd == null && "".equals(pwd)) {
				return false;
			}
			if(toEmail == null && "".equals(toEmail)) {
				return false;
			}
			if(host == null && "".equals(host)) {
				return false;
			}
			if(port == null && "".equals(port)) {
				return false;
			}
			  MailSenderInfo mailInfo = new MailSenderInfo();   
		      mailInfo.setMailServerHost(host);   
		      mailInfo.setMailServerPort(port);   
		      mailInfo.setValidate(true);   
		      mailInfo.setUserName(formEmail);   
		      mailInfo.setPassword(pwd);//您的邮箱密码   
		      mailInfo.setFromAddress(formEmail);   
		      mailInfo.setToAddress(toEmail);   
		      mailInfo.setSubject("代理天下-管理登验证码!");   
		      mailInfo.setContent(code);   
		        //这个类主要来发送邮件  
		      SimpleMailSender sms = new SimpleMailSender();  
	          sms.sendTextMail(mailInfo);//发送文体格式   
	          sms.sendHtmlMail(mailInfo);//发送html格式  
	          
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	/**
	 * 用户注册时验证邮箱是否重复
	 * @param email
	 * @return
	 */
	public boolean validEmail(String email) {
		String hql = " from User where email='"+email+"'";
		List<User> list = userDao.find(hql);
		if(list.size()>0) {
			return false;
		} else {
			return true;
		}
	}
	public void setPriceDao(PriceDao priceDao) {
		this.priceDao = priceDao;
	}
	public void setRecordDao(RecordDao recordDao) {
		this.recordDao = recordDao;
	}
	
	public UserTempDao getUserTempDao() {
		return userTempDao;
	}
	public void setUserTempDao(UserTempDao userTempDao) {
		this.userTempDao = userTempDao;
	}
	@Override
	public String findUserRole(Object[] args) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void updateTitle(Object[] params) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public UserTemp getUserTempById(Integer id) {
		return userTempDao.get(id);
	}
	@Override
	public Integer saveUserTemp(UserTemp userTemp) {
		return (Integer) userTempDao.create(userTemp);
	}
	@Override
	public void deleteUserTemp(UserTemp userTemp) {
		userTempDao.remove(userTemp);
	}
	@Override
	public boolean validUserName(UserTemp userTemp) {
		String hql = " from User u where u.email='"+userTemp.getEmail()+"' or u.username='"+userTemp.getUsername()+"'";
		List list = userDao.find(hql);
		if(list.size() > 0) {
			return true;
		}
		return false;
	}
	
	
}
